import logging

from google.appengine.ext import webapp

register = webapp.template.create_template_register()

def truncate(value,maxsize,stopper = '...'):
    """ truncates a string to a given maximum
        size and appends the stopper if needed """
    stoplen = len(stopper)
    if len(value) > maxsize and maxsize > stoplen:
       return value[:(maxsize-stoplen)] + stopper
    else:
       return value[:maxsize]

def page_range(value, totalhits = 10):
    npage = int(value)
    total_pages = int(totalhits)/ 10
    if npage < 9 and total_pages <= 10:
        return range(0,total_pages)
    if npage < 9 and total_pages > 10:
        return range(0,10)
    elif npage >= 9 and npage < (total_pages - 10):
        return range(npage - 10, npage + 10)
    else:
        return range(npage - 9, total_pages)
	   
def capitalize(value):
	return value.capitalize()

def minus(value, m):
    return value - m

def mult(value, m):
    return value * m

def thousands(value):
    number = str(value)[::-1]
    result = []
    n = 0
    while n < len(number):
        if n > 0 and n % 3 == 0:
            result += ","
        result += str(number[n])
        n+=1
    return ''.join(result)[::-1]
	
def byte_to_kilobyte(value):
	return int(value) / 1024

register.filter(capitalize)
register.filter(truncate)
register.filter(page_range)
register.filter(thousands)
register.filter(byte_to_kilobyte)
register.filter(minus)
register.filter(mult)
